package com.uyayo.system.authority.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.uyayo.system.authority.entity.SysRoleResource;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.authority.pojo.SysUserPO;
import com.uyayo.system.authority.entity.SysUserOrganization;
import com.uyayo.system.authority.model.SysUserCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uyayo.framework.common.exception.CustomException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.common.util.CodeUtil;
import com.uyayo.framework.pagehelper.pojo.OrderBy;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.util.OrderByUtil;
import com.uyayo.system.authority.entity.SysUserRole;
import com.uyayo.system.authority.mapper.SysUserMapper;
import com.uyayo.system.authority.mapper.SysUserOrganizationMapper;
import com.uyayo.system.authority.mapper.SysUserRoleMapper;
import com.uyayo.system.authority.service.SysUserService;


@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

	private final SysUserMapper sysUserMapper;


	private final SysUserRoleMapper userRoleMapper;

	private final SysUserOrganizationMapper userOrganizationMapper;

	@Autowired
	public SysUserServiceImpl(@Qualifier(value = "sysUserMapper") SysUserMapper sysUserMapper, SysUserRoleMapper userRoleMapper, SysUserOrganizationMapper userOrganizationMapper) {
		this.sysUserMapper = sysUserMapper;
		this.userRoleMapper = userRoleMapper;
		this.userOrganizationMapper = userOrganizationMapper;
	}

	//@Cacheable(value = "getUserById",key="#id")
	@Override
	public SysUser getUserById(String id) throws Exception{
		SysUser user =sysUserMapper.selectByPrimaryKey(id);
		//中间对商品信息进行业务处理
		if(user==null){
			throw new CustomException("该用户信息不存在！");
		}
		return user;
	}
	

	@Override
	public SysUserPO getUserToRole(String userId) {
		return sysUserMapper.getUserToRole(userId);
	}
	
	@Override
	public List<SysUser> selectUser(SysUserCondition sysUserQUERY) {
		Example example = new Example(SysUser.class);  
		example.createCriteria();
		return sysUserMapper.selectByExample(example);
	}
	
	@Override
	public PageBean<SysUser> selectUserByPaging(PageBean<SysUser> pageBean,SysUserCondition sysUserCondition) {

		List<SysUser> userList;
		//分页处理
		List<OrderBy> orderBies = new ArrayList<>();
		orderBies.add(new OrderBy("createdTime", "created_time"));
		orderBies.add(new OrderBy("modifiedTime", "modified_time"));

		OrderByUtil  orderByUtil = new OrderByUtil();
		String orderBy = orderByUtil.getOrderBy(orderBies, pageBean.getOrderField(), pageBean.getOrderDirection());
		PageHelper.startPage(pageBean.getPageCurrent(), pageBean.getPageSize());
		
		Example example = new Example(SysUser.class);
		if(!StringUtils.isEmpty(orderBy)){
			example.setOrderByClause(orderBy);
		}
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(sysUserCondition.getLoginname())){
			criteria.andLike("loginname","%"+sysUserCondition.getLoginname()+"%");
		}
		if(sysUserCondition.getBeginCreatedTime()!=null || sysUserCondition.getEndCreatedTime()!=null){
			criteria.andBetween("createdTime", sysUserCondition.getBeginCreatedTime(), sysUserCondition.getEndCreatedTime());
		}
		userList = sysUserMapper.selectByExample(example);

		//取记录总条数
		PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
		pageBean.setTotalCount(pageInfo.getTotal());
		pageBean.setList(userList);
		return pageBean;
	}
	

	@Override
	public int saveUser(SysUser user) {
		return sysUserMapper.insertSelective(user);
	}

	@Override
	public SysUser getUserByUpdateTestOnly(String loginname) {
		SysUser sysUser = new SysUser();
		sysUser.setLoginname(loginname);
		return sysUserMapper.selectOne(sysUser);
	}

	@Override
	public int updateUser(SysUser user) {
		return sysUserMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public int deleteUser(String id) throws CustomException {
		Example example = new Example(SysUserRole.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", id);
		int count = userRoleMapper.selectCountByExample(example);
		if(count>0){
			throw new CustomException("该用户已经授权角色，请先解除授权！");
		}
		return sysUserMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Result assignUserRoles(String ids,String userId) {
		Result customResult = new Result(200,"保存成功");

		String[] roleIdArr = ids.split(",");
		
		List<SysUserRole> userRoles = new ArrayList<>();
		if(roleIdArr.length>0 && !roleIdArr[0].equals("")){
			for (String aRoleIdArr : roleIdArr) {
				SysUserRole userRole = new SysUserRole();
				userRole.setId(CodeUtil.getTimeSequenceAsRandomCode());
				userRole.setUserId(userId);
				userRole.setRoleId(aRoleIdArr);
				userRoles.add(userRole);
			}
		}
		int deleteCount;
		int saveCount = 0;
		try {
			Example example = new Example(SysUserRole.class);  
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("userId", userId);
			deleteCount = userRoleMapper.deleteByExample(example);
			if(userRoles.size()>0){
				saveCount = userRoleMapper.insertUserRoleByList(userRoles);
			}
			customResult.setMessage("删除"+deleteCount+"条记录，保存"+saveCount+"条记录！");

		} catch (Exception e) {
			customResult=Result.build(500, "保存失败！");
			e.printStackTrace();
		}
		return customResult;
	}

	@Override
	public Result grantUserOrganizations(String ids,String userId) {
		Result customResult = new Result(200,"保存成功");

		String[] organizationIdArr = ids.split(",");
		
		List<SysUserOrganization> userOrganizations = new ArrayList<>();
		if(organizationIdArr.length>0 && !organizationIdArr[0].equals("")){
			for (String anOrganizationIdArr : organizationIdArr) {
				SysUserOrganization userOrganization = new SysUserOrganization();
				userOrganization.setId(CodeUtil.getTimeSequenceAsRandomCode());
				userOrganization.setUserId(userId);
				userOrganization.setOrganizationId(anOrganizationIdArr);
				userOrganizations.add(userOrganization);
			}
		}
		int deleteCount;
		int saveCount = 0;
		try {
			Example example = new Example(SysUserOrganization.class);  
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("userId", userId);
			deleteCount = userOrganizationMapper.deleteByExample(example);
			if(userOrganizations.size()>0){
				saveCount = userOrganizationMapper.insertUserOrganizationByList(userOrganizations);
			}
			customResult.setMessage("删除"+deleteCount+"条记录，保存"+saveCount+"条记录！");
		} catch (Exception e) {
			customResult=Result.build(500, "保存失败！");
			e.printStackTrace();
		}
		return customResult;
	}
	
	@Override
	public SysUser getUserByLoginname(String loginname) {
		SysUser sysUser = new SysUser();
		sysUser.setLoginname(loginname);
		return sysUserMapper.selectOne(sysUser);
	}
	
}
